<template lang="pug">
mt-dialog(
  v-model="appmodel"
  cancel-text="取消"
  title="送检明细"
  :on-close="updateModel"
  :on-cancel="updateModel"
  hide-confirm
  size="large"
  height="full"
)
  DataPage(
    v-bind="pageParams"
  )
    .container(
      v-if="isAdd"
    )
      span(style="color: rgb(53, 160, 0); ") 同一送检批次业务来源、标本类型需要一致,已选标本数量: {{ quantityNumber  }}
      div
        mt-button(
          type="primary"
          label="确认送检"
          :loading ="loadingMap.batchGenerateSendInspection"
          :disabled="actualSpecimen?.length == 0"
          @click="sendInspectionButton"
        )
    mt-table(
      v-bind="tableProps"
    )

sendinspectionModel(v-model="sendinspectionModelShow" :selectionRow="actualSpecimen"  @message-to-parent="messageToParent")
</template>

<script setup lang="ts">
import {
  type FormItemProps,
  type DataPageProps,
  type TableProps,
  useNotify,
  DataPage,
} from "@scmt/common-components";
import { type QueryPagination, useApi } from "@scmt/core-api";
import {
  type SpecimenEntity,
  type SpecimenQueryParams,
} from "@scmt/api-lis-specimen";
import { useRequest } from "@scmt/common-hooks";
import sendinspectionModel from "./sendinspectionShow.vue";
import { useUtils } from "@scmt/lib-utils";
import {
  ESpecimenStatus,
  ESpeimenTableColumnKey,
  specimenColumns,
} from "@scmt/api-common";
import { useGroup } from "../../composable/group";

//添加 Props属性
const props = defineProps({
  batchNumber: {
    type: String,
    default: "",
  },
});
const appmodel = defineModel({
  default: false,
});
const emit = defineEmits(["message-to-parent"]);

const $api = useApi();
const $notify = useNotify();
const $utils = useUtils();

const { batchNumber } = toRefs(props);
const sendinspectionModelShow = ref(false);
const selectionRow = ref<SpecimenEntity[]>([]);

const queryPramas = reactive<SpecimenQueryParams>($$createQueryParams());

const { request, data, loadingMap } = useRequest(
  {
    tableData: (q: any) => {
      const params = Object.assign({}, queryPramas, q, {
        // 批次号赋值，如果不存在需要
        batchNumber: batchNumber.value ? batchNumber.value : "",
        state: batchNumber.value ? "" : ESpecimenStatus.Collection,
      });
      return $api.lis.specimen.getSpecimenPageList(params);
    },
    batchGenerateSendInspection: (params: any) => {
      return $api.lis.specimen.batchGenerateSendInspection(params).then(() => {
        $notify.success("送检成功");
        emit("message-to-parent");
        appmodel.value = false;
      });
    },
    categoryList: () => {
      return $api.lis.specimen.category.listAsOptions();
    },
    patientTypeList: () => {
      return $api.dict.item.listAsOptions("patient-type");
    },
  },
  {
    tableData: {
      items: [] as SpecimenEntity[],
      pagination: {
        pageNum: queryPramas.pageNum,
        pageSize: queryPramas.pageSize,
        total: 0,
      },
    },
    categoryList: [],
    patientTypeList: [],
  }
);

const { tableData } = toRefs(data);

const { getCellClassName, spanMethod, getGroupKey } = useGroup(tableData);

const actualSpecimen = computed(() => {
  const selectKeys = Array.from(
    new Set(selectionRow.value.map((item) => item[getGroupKey(item)]))
  );

  return tableData.value.items.filter((i) =>
    selectKeys.includes(i[getGroupKey(i)])
  );
});
const isAdd = computed(() => !Boolean(batchNumber.value));
const quantityNumber = computed(() => actualSpecimen.value.length);
const queryFields = computed<FormItemProps[]>(() => [
  {
    prop: "specimenTypeId",
    label: "标本类型",
    as: "select",
    options: {
      options: data.categoryList,
      clearable: false,
    },
    visible: isAdd.value,
  },
  {
    prop: "source",
    label: "业务来源",
    as: "select",
    options: {
      options: data.patientTypeList,
      clearable: false,
    },
    visible: isAdd.value,
  },
  {
    prop: "today",
    label: "是否当天",
    as: "checkbox",
    span: 2,
    options: {
      loadMethod: () => {
        return [
          {
            label: "是",
            value: true,
          },
        ];
      },
    },
    visible: isAdd.value,
  },
  {
    prop: "outpatientNumber",
    label: "业务编号",
  },
  {
    prop: "patientName",
    label: "患者姓名",
  },
  {
    prop: "barcode",
    label: "标本条码",
  },
  {
    prop: "billingDepartment",
    label: "开单科室",
    as: "select",
    options: {
      render: "office-table",
      loadMethod: $api.upms.org.listAsOptions,
    },
    visible: isAdd.value,
  },
  {
    prop: "inspectionTime",
    label: "开单时间",
    as: "date",
  },
]);
const pageParams = computed<DataPageProps>(() => {
  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    queryFields: queryFields.value,
    onQuery: () => request("tableData"),
    columns: 4,
    flex: true,
  };

  return dataPageProps;
});

const tableColumns = computed(() => {
  const preColumns: TableProps["columns"] = isAdd.value
    ? [
        {
          prop: "_selection",
          type: "selection",
          selectable: ({
            specimenTypeId: rowSpecimenTypeId,
            source: rowSource,
          }) => {
            if (selectionRow.value.length) {
              const { specimenTypeId, source } = selectionRow.value[0];
              return (
                rowSpecimenTypeId === specimenTypeId && rowSource === source
              );
            }
            return true;
          },
        },
      ]
    : [];

  const baseColumns: TableProps["columns"] = [
    specimenColumns[ESpeimenTableColumnKey.Source],
    specimenColumns[ESpeimenTableColumnKey.OutpatientNumber],
    specimenColumns[ESpeimenTableColumnKey.PatientName],
    specimenColumns[ESpeimenTableColumnKey.Sex],
    specimenColumns[ESpeimenTableColumnKey.Age],
    specimenColumns[ESpeimenTableColumnKey.ApplicationProject],
    specimenColumns[ESpeimenTableColumnKey.SpecimenTypeId],
    specimenColumns[ESpeimenTableColumnKey.Barcode],
    specimenColumns[ESpeimenTableColumnKey.State],
    specimenColumns[ESpeimenTableColumnKey.BillingDepartment],
    specimenColumns[ESpeimenTableColumnKey.BillingDoctor],
    specimenColumns[ESpeimenTableColumnKey.BillingTime],
    {
      prop: "collectionTime",
      label: "采集时间",
      format: "datetime",
    },
    specimenColumns[ESpeimenTableColumnKey.Urgent],
  ];
  return preColumns.concat(baseColumns);
});

const tableProps = computed(() => {
  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: tableColumns.value,
    onPaginate: (pagination: QueryPagination) =>
      request("tableData", pagination),
    onSelectionChange: (selection: SpecimenEntity[]) => {
      selectionRow.value = selection;
    },
    highlightCurrentRow: true,
    hideHeaderSelection: true,
    cellClassName: getCellClassName,
    spanMethod: spanMethod,
  };
  return tableProps;
});

watch(appmodel, (visible: boolean) => {
  if (visible) {
    Object.assign(queryPramas, $$createQueryParams(isAdd.value));
    request(["tableData", "patientTypeList", "categoryList"]);
  }
});

const updateModel = () => {
  appmodel.value = false;
};

//标本送检
const sendInspectionButton = () => {
  sendinspectionModelShow.value = true;
};

const messageToParent = () => {
  appmodel.value = false;
  emit("message-to-parent");
};

function $$createQueryParams(isAdd = false): SpecimenQueryParams {
  const queryPramas: SpecimenQueryParams = {
    source: "",
    specimenTypeId: "",
    startDate: $utils.date().startOf("date").format("YYYY-MM-DD HH:mm:ss"),
    endDate: $utils.date().endOf("date").format("YYYY-MM-DD HH:mm:ss"),
    pageNum: 1,
    pageSize: 20,
  };

  return queryPramas;
}
</script>

<style lang="less" scoped>
.container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
@text-size: calc(var(--unit) * 20);
:deep(.el-table) {
  &__body {
    .group-text {
      position: relative;

      &::before {
        position: absolute;
        display: inline-block;
        color: var(--el-color-primary);
        font-size: var(--mt-fs-mini);
        top: 50%;
        transform: translate(-50%, -50%);
        content: "合";
        font-weight: 700;
        width: @text-size;
        height: @text-size;
        text-align: center;
        line-height: @text-size;
        border-radius: 50%;
        background-color: var(--el-color-white);
        z-index: 1;
      }
    }

    .group-text--offset {
      position: relative;
      &::before {
        top: -50%;
        transform: translate(-50%, 50%);
      }
    }
  }
}
</style>
